package com.mcu32.bright.util;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.mcu32.bright.config.OneNetProperties;
import com.mcu32.bright.model.Result;
import com.mcu32.bright.model.bo.DevicePropertyBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class OneNetUtil {

    @Autowired
    private OneNetProperties oneNetProperties;

    public Result invoke(String nameSpace, String action, String requestStr , Method method) {
        String responseBody = null;
        try {

            String url = createUrl(nameSpace, action ,method ,requestStr);
            log.debug("OneNet-URL:{}  , 参数： {}", url, requestStr);
            HttpRequest httpRequest = null;
            if (method == Method.GET){
                httpRequest = HttpRequest.get(url)
                        .timeout(60000);
            }else if (method == Method.POST){
                httpRequest = HttpRequest.post(url)
                        .header(Header.CONTENT_TYPE, "application/json")
                        .body(requestStr)
                        .timeout(60000);
            }

            // 获取token
            String token = TokenUtil.getToken();
            httpRequest.header("Authorization", token);
            responseBody = httpRequest.execute().body();


            log.debug("Result:{}", responseBody);
        } catch (Exception e) {
            log.error("Result,api error:{}", responseBody, e);
        }
        return JSONUtil.toBean(responseBody, Result.class);
    }

    public String createUrl(String nameSpace,String action, Method method ,String requestStr){
        OneNetProperties.CommonInfo commonInfo = oneNetProperties.getCommonInfo();
        String url = commonInfo.getUrl();
        StringBuilder stringBuilder = new StringBuilder(url);
        String url1 = url.replace("namespace", nameSpace);
        String url2 = url1.replace("xxxx", action);
        String url_param= "";
        if (method == Method.GET){
            DevicePropertyBo devicePropertyBo = JSONUtil.toBean(requestStr, DevicePropertyBo.class);
            String project_id = devicePropertyBo.getProject_id();
            String product_id = devicePropertyBo.getProduct_id();
            String device_name = devicePropertyBo.getDevice_name();
           url_param = "&project_id="+project_id+ "&product_id="+product_id+ "&device_name="+device_name;
        }
        return url2+url_param;

    }
}
